package com.workflow.listener;

import com.oa.pojo.Role;
import com.oa.pojo.User;
import com.oa.service.DeptService;
import com.oa.service.LeaveService;
import com.oa.service.UserService;
import com.oa.service.impl.DeptServiceImpl;
import com.oa.utils.MyWebUtils;
import org.activiti.engine.delegate.DelegateTask;
import org.activiti.engine.delegate.TaskListener;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

/**
 * @Author Str
 * @Date 2021/12/6 14:33
 * @Description :监听器
 * 这个监听器是由Activiti而非Spring创建，所以无法注入对象
 */
public class LeaveTaskHandler implements TaskListener {
    //    @Autowired
//    private UserService userService;
//    @Autowired
//    private DeptService deptService;
//    @Autowired
//    private LeaveService leaveService;
    private LeaveService leaveService;
    private UserService userService;

    public LeaveTaskHandler() {
        // 根据上下文加载器从ioc容器中获取bean
        leaveService = MyWebUtils.getBean(LeaveService.class);
        userService = MyWebUtils.getBean(UserService.class);
    }

    @Override
    public void notify(DelegateTask task) {
        // 1、获取当前处理事务时的用户对象，从会话域拿
        User currentUser = MyWebUtils.getCurrentUser();
        // 2、获取当前用户的角色

        // 3、获取任务ID，流程实例ID
        String taskID = task.getId();
        String proInsID = task.getProcessInstanceId();
        String deptId = currentUser.getDeptId();
        String leaderID = null;
        // 4、判断是员工还是领导 leader（部门主管） / employee（雇员）
        String roleId = userService.getRoleId(currentUser.getId());
        // 本部门leader审批
        if (roleId.equals("r03") || roleId.equals("r04") || roleId.equals("r05")) {
            // 根据部门ID获取所在部门领导ID
            leaderID = leaveService.getDeptLeaderID(deptId);
        }
        // 更高级部门leader审批
        else if (roleId.equals("r02")) {
            leaderID = leaveService.getHigherLevelDeptLeaderId(deptId);
        }
        // boss审批
        if (leaderID == null) {
            leaderID = "u03";
        }
        System.out.println("======================================");
        System.out.println("leaderID:" + leaderID);
        System.out.println("======================================");

        // 设置新建节点的办理人
        task.setAssignee(leaderID);
        // 更新t_leave表(办理人+任务ID)
        leaveService.updateAssigneeAndTask(proInsID, taskID, leaderID);
    }
}
